import React from 'react';
import { Handle, Position } from '@xyflow/react';
import { Box, Typography, IconButton, Chip } from '@mui/material';
import { PlayCircle as PlayCircleIcon } from '@mui/icons-material';
import { NodeData, NODE_TYPES } from './NodeTypes';

interface MachineLearningNodeProps {
  id: string;
  data: NodeData;
  selected: boolean;
}

// 机器学习节点组件
const MachineLearningNode: React.FC<MachineLearningNodeProps> = ({ id, data, selected }) => {
  // 根据机器学习类型选择颜色
  const getMLNodeColor = () => {
    switch (data.type) {
      case NODE_TYPES.LOGISTIC_REGRESSION: return '#9C27B0'; // 紫色
      case NODE_TYPES.RANDOM_FOREST: return '#673AB7'; // 深紫
      case NODE_TYPES.SVM: return '#3F51B5'; // 靛蓝
      default: return '#9c27b0';
    }
  };

  // 调试输出
  React.useEffect(() => {
    console.log(`MachineLearningNode ${id} 类型 ${data.type} 的数据:`, data);
    console.log(`MachineLearningNode ${id} 的执行结果:`, data.lastExecutionResult);
    if (data.lastExecutionResult?.metrics) {
      console.log(`MachineLearningNode ${id} 的metrics:`, data.lastExecutionResult.metrics);
    }
  }, [id, data]);

  const borderColor = getMLNodeColor();
  const bgColor = selected ? `${borderColor}22` : '#fff';

  // 获取模型精度（如果存在）
  const getAccuracy = () => {
    if (data.lastExecutionResult?.metrics?.accuracy) {
      console.log(`节点 ${id} 获取到accuracy:`, data.lastExecutionResult.metrics.accuracy);
      return (data.lastExecutionResult.metrics.accuracy * 100).toFixed(2) + '%';
    }
    return null;
  };

  // 获取训练样本数量
  const getTrainingSamples = () => {
    if (data.lastExecutionResult?.training_info?.n_samples_train) {
      return data.lastExecutionResult.training_info.n_samples_train;
    }
    return null;
  };

  const accuracy = getAccuracy();
  const trainingSamples = getTrainingSamples();

  return (
    <Box
      sx={{
        padding: 1.5,
        borderRadius: 2,
        background: bgColor,
        minWidth: 150,
        textAlign: 'center',
        fontSize: '14px',
        color: '#333',
        border: `2px solid ${borderColor}`,
        boxShadow: selected
          ? `0 0 10px ${borderColor}66`
          : '0 2px 8px rgba(0,0,0,0.1)',
        transition: 'all 0.3s ease',
        '&:hover': {
          boxShadow: `0 0 15px ${borderColor}44`,
          transform: 'translateY(-2px)',
        },
        position: 'relative',
      }}
    >
      {/* 节点标题 */}
      <Typography
        component="div"
        sx={{
          fontWeight: 600,
          mb: 0.5,
          color: '#333',
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
        }}
      >
        {data.label || ''}
      </Typography>
      
      {/* 节点类型标签 */}
      <Typography
        variant="caption"
        component="div"
        sx={{
          opacity: 0.7,
          mb: 1,
          fontSize: '0.7rem',
        }}
      >
        {data.type?.replace(/_/g, ' ') || ''}
      </Typography>
      
      {/* 显示模型精度（如果存在） */}
      {accuracy && (
        <Box sx={{ mt: 1, display: 'flex', justifyContent: 'center', gap: 0.5 }}>
          <Chip
            label={`准确率: ${accuracy}`}
            size="small"
            color="primary"
            variant="outlined"
            sx={{ fontSize: '0.7rem' }}
          />
        </Box>
      )}
      
      {/* 执行图标 */}
      <IconButton
        size="small"
        sx={{
          position: 'absolute',
          top: -12,
          right: -12,
          backgroundColor: '#fff',
          border: `1px solid ${borderColor}`,
          '&:hover': {
            backgroundColor: '#f0f0f0',
            transform: 'scale(1.1)',
          },
          transition: 'all 0.2s ease',
          boxShadow: '0 2px 5px rgba(0,0,0,0.1)',
        }}
        onClick={(e) => {
          e.stopPropagation();
          const event = new CustomEvent('execute-node', { detail: { nodeId: id } });
          window.dispatchEvent(event);
        }}
      >
        <PlayCircleIcon fontSize="small" color="primary" />
      </IconButton>

      {/* 输入端口 */}
      <Handle
        type="target"
        position={Position.Top}
        style={{
          background: borderColor,
          width: '10px',
          height: '10px',
          border: '2px solid #fff',
        }}
      />

      {/* 输出端口 */}
      <Handle
        type="source"
        position={Position.Bottom}
        style={{
          background: borderColor,
          width: '10px',
          height: '10px',
          border: '2px solid #fff',
        }}
      />
    </Box>
  );
};

export default MachineLearningNode; 